<template>
  <section class="main">
    <el-form
      ref="myFormRef"
      :model="myForm"
      :rules="rules"
      label-width="0px"
      size="large"
    >
      <h2>欢迎使用管理系统</h2>
      <el-form-item prop="mobile">
        <el-input
          v-model="myForm.mobile"
          placeholder="请输入电话号码"
          type="tel"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="myForm.password"
          type="password"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item class="item-btns">
        <el-button
          type="primary"
          native-type="submit"
          @click.prevent="submitForm(myFormRef)"
          >登录</el-button
        >
        <el-button type="primary" @click="resetForm(myFormRef)">清空</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script setup lang="ts">
import { ajax } from "@/util/request";

import md5 from "js-md5";

import { reactive, ref } from "vue";

import { useRouter } from "vue-router";

import { useStore } from "vuex";

import type { FormInstance, FormRules } from "element-plus";

let myFormRef = ref<FormInstance>();


let myForm = reactive({
  mobile: "",
  password: "",
});

let rules = reactive<FormRules>({
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "手机号码必须是11位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 19, message: "请输入6到19位密码", trigger: "blur" },
  ],
});

const router = useRouter();
const store = useStore();

function submitForm(myFormRef: FormInstance) {
  // validate：校验表单
  myFormRef.validate((valid) => {
    // 校验失败
    if (!valid) {
      console.log("校验失败！");
      return;
    }
    // 校验成功
    console.log("校验成功");
    let data = {
      ...myForm,
    };
    data.password = md5(data.password);
    // 发起异步请求
    ajax("/login/adminLogin", data).then((res) => {
      // 登录成功
      if (res.data.status > 0) {
        // 保存本地数据
        store.commit("setAdmin",res.data.result_data);
        
        //  跳转到首页
        router.push("/index");
      }
    });
  });
}

function resetForm(myFormRef: FormInstance) {
  myFormRef.resetFields();
}
</script>

<style scoped>
.el-form {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 20px;
  padding: 40px 60px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  margin: auto;
}

.el-form > h2 {
  padding: 10px;
  text-align: center;
}

.main {
  background-color: #333333;
  height: 100vh;
}
</style>
<style>
.item-btns > .el-form-item__content {
  justify-content: center;
}
</style>